package com.moyq5.permit.center.web;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;

/**
 * @author Moyq5
 * @date 2019年8月13日
 */
public class ShiroFormFilter extends FormAuthenticationFilter implements ShiroAppliedPathsResetProcessor {
private List<String> origins;
    
    public ShiroFormFilter(List<String> origins) {
        this.origins = origins;
    }
    
    @Override
    protected void redirectToLogin(ServletRequest request, ServletResponse response) throws IOException {
        String origin = "http://localhost:8080";
        if (origins.contains(((HttpServletRequest)request).getHeader("Origin"))) {
            origin = ((HttpServletRequest)request).getHeader("Origin");
        }
        ((HttpServletResponse)response).setHeader("Access-Control-Allow-Origin", origin);
		((HttpServletResponse)response).setHeader("Access-Control-Allow-Credentials", "true");
		((HttpServletResponse)response).setHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, PATCH");
		if (((HttpServletRequest)request).getMethod().equals("OPTIONS")) {
			((HttpServletResponse)response).setHeader("Access-Control-Allow-Headers","Content-Type");
		} else {
			((HttpServletResponse)response).sendError(403, "no login");
		}
		
	}
	
	@Override
	public void clearAppliedPaths() {
		appliedPaths.clear();
	}

}
